const axios = require("axios");

let homeController = {
    test: function (writeDataCallback, argObj) {
        writeDataCallback('{"msg":"test is ok"}');
    },
}
let caipiaoController = {
    getRecent10Records: function (writeDataCallback, argObj) {
        let url = "http://www.cwl.gov.cn/cwl_admin/front/cwlkj/search/kjxx/findDrawNotice?name=ssq&issueCount=10";
        let config = {
            headers: {
                "Accept": "application/json, text/javascript, */*; q=0.01",
                "Accept-Encoding": "gzip, deflate",
                "Accept-Language": "zh-CN,zh;q=0.9",
                "Cache-Control": "no-cache",
                "Connection": "keep-alive",
                "Host": "www.cwl.gov.cn",
                "Pragma": "no-cache",
                "Referer": "http://www.cwl.gov.cn/kjxx/ssq/",
                "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.63 Safari/537.36",
                "X-Requested-With": "XMLHttpRequest"
            }
        }
        axios.get(url, config)
            .then(reqResult => {
                let list = reqResult.data.result;
                list = list.map(n => ({ blue: parseInt(n.blue), red: n.red.split(",").map(n => parseInt(n)), code: n.code }));
                writeDataCallback(list);
            })
            .catch(function (error) {
                console.log(error);
            });
    }
}

/**
 * 
 * @param {*} controllerName 控制器名称
 * @param {*} actionName 动作名称
 * @param {*} argObj 参数对象
 * @param {*} writeDataCallback 写入数据的回调
 */
let execute = (controllerName, actionName, argObj, writeDataCallback) => {
    if (controllerName.indexOf("Controller") > -1) {
        controllerName = controllerName.replace("Controller", "");
    }
    let controller1 = apiManager[controllerName];
    if (controller1 == undefined) {
        throw new Error("控制器不存在");
    }
    let action1 = controller1[actionName];
    if (action1 == undefined) {
        throw new Error("函数不存在");
    }
    action1(writeDataCallback, argObj);
}

const apiManager = {
    home: homeController,
    caipiao: caipiaoController,
    execute: execute
}

module.exports = apiManager;